<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card -->
    <el-card>
      <!-- 提示消息 -->
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        :model="addruleForm"
        :rules="addruleFormRules"
        ref="addruleFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="active"
          :tab-position="tabPosition"
          :before-leave="beforeLeaveFunction"
          @tab-click="tabClickChange(active)"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addruleForm.goods_cat"
                :options="goodsCateList"
                :props="configInfo"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyFormList" :label="item.attr_name" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="items" v-for="(items,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in onlyFormList">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="ImgUploadHeader"
              :on-success="imgUploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!--商品内容-->
          <el-tab-pane label="商品内容" name="4" style="height:900px;">
            <el-form-item>
              <!-- 富文本编辑器 -->
              <quill-editor
                v-model="addruleForm.goods_introduce"
                class="editorHere"
                style="height:600px;"
              ></quill-editor>
            </el-form-item>

            <el-form-item>
              <!-- button按钮 -->
              <el-button type="primary" class="addButton" @click="add()">提交</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="30%">
      <span>
        <img class="imgPreview" :src="imgPreviewUrl" alt />
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";

export default {
  data() {
    return {
      // 预览图片区域可视化
      imgDialogVisible: false,
      //预览图片路径
      imgPreviewUrl: "",
      // 图片上传请求头
      ImgUploadHeader: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 静态属性列表
      onlyFormList: [],
      // 动态参数列表
      manyFormList: [],
      //   商品分类信息
      goodsCateList: [],
      //   级联选择配置信息
      configInfo: {
        checkStrictly: false,
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 添加商品Form表单
      addruleForm: {
        goods_name: "",
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      //   添加商品Form表单验证规则
      addruleFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_introduce: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },

      // 标签页方向
      tabPosition: "left",
      // 标签页active
      active: "0",
    };
  },
  computed: {
    // 获取商品分类的三级id
    thirdId() {
      if (this.addruleForm.goods_cat.length === 3) {
        return this.addruleForm.goods_cat[2];
      } else {
        return null;
      }
    },
    // 步骤条activeIndex
    activeIndex() {
      return parseInt(this.active);
    },
  },
  methods: {
    // 添加商品
    add() {
      // 表单预验证
      this.$refs.addruleFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请填写必填项！");
        } else {
          // lodash cloneDeep(obj)
          const form = _.cloneDeep(this.addruleForm);
          form.goods_cat = form.goods_cat.join(",");

          this.manyFormList.forEach((item) => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(" "),
            };
            this.addruleForm.attrs.push(newInfo);
          });
          this.onlyFormList.forEach((item) => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(" "),
            };
            this.addruleForm.attrs.push(newInfo);
          });
          form.attrs = this.addruleForm.attrs;
          // 发起网络请求
          const { data: res } = await this.$http.post("goods", form);
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.success("创建商品成功！");
            this.$router.push("/goods");
          }
        }
      });
    },
    // 图片上传成功
    imgUploadSuccess(response) {
      console.log("图片上传成功：");
      console.log(response);
      if (response.meta.status == 200) {
        this.addruleForm.pics.push({
          pic: response.data.tmp_path,
        });
        console.log(this.addruleForm);
      }
    },
    // 图片预览事件
    handlePreview(file) {
      console.log("预览：");
      console.log(file);
      this.imgPreviewUrl = file.response.data.url;
      this.imgDialogVisible = true;
    },
    // 图片删除事件
    handleRemove(file) {
      // 查找删除图片的索引
      const i = this.addruleForm.pics.findIndex((item) => {
        item.pic == file.response.data.tmp_path;
      });
      this.addruleForm.pics.splice(i);
      console.log("删除图片后：");
      console.log(this.addruleForm);
    },
    //   标签页切换前触发
    beforeLeaveFunction(activeName, oldActiveName) {
      console.log(oldActiveName);
      console.log(activeName);
      if (oldActiveName === "0" && this.addruleForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类！");
        return false;
      }
    },
    //   级联选择框change事件
    handleChange() {
      // 只能选择三级分类
      if (this.addruleForm.goods_cat.length !== 3) {
        this.addruleForm.goods_cat = [];
      } else {
        console.log(this.addruleForm.goods_cat);
      }
    },
    // 标签页切换时触发
    tabClickChange(active) {
      console.log("被选中的标签页：");
      console.log(active);
      if (active === "1") {
        this.getManyList();
      }
      if (active === "2") {
        this.getOnlyList();
      }
    },
    // 获取静态属性
    async getOnlyList() {
      const { data: res } = await this.$http.get(
        `categories/${this.thirdId}/attributes`,
        {
          params: { sel: "only" },
        }
      );
      if (res.meta.status !== 200) {
        console.log(res.meta.msg);
      } else {
        console.log("静态属性：");
        console.log(res.data);
        this.onlyFormList = res.data;
      }
    },
    // 获取动态参数
    async getManyList() {
      // 发起网络请求
      const { data: res } = await this.$http.get(
        `categories/${this.thirdId}/attributes`,
        {
          params: { sel: "many" },
        }
      );
      if (res.meta.status !== 200) {
        console.log(res.meta.msg);
      } else {
        console.log("动态参数：");
        console.log(res.data);
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        this.manyFormList = res.data;
      }
    },
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.goodsCateList = res.data;
      }
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="less" scoped>
.el-steps {
  margin: 10px;
}
.el-form-item {
  text-align: left;
}
.imgPreview {
  width: 100%;
}

.el-card {
  height: 1300px;
}
.el-button {
  cursor: pointer;
}

.addButton {
  margin: 10px;
}
.el-form-item__content {
  height: 300px !important;
}
</style>